﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;


namespace DataService.Office.Word
{
    public class XmlBodyContent
    {
        public static void BodyAppendText(DocumentFormat.OpenXml.Wordprocessing.Body body, string text)
        {
            Paragraph paragraph = new Paragraph();
            Run run = new Run();
            run.Append(new Text(text));
            paragraph.Append(run);
            body.Append(paragraph);

        }
        /// <summary>
        /// 当前段落追加文本
        /// </summary>
        /// <param name="paragraph">当前段落</param>
        /// <param name="text"></param>
        public static void ParagraphAppendText(Paragraph paragraph, string text)
        {
            Run run = new Run();
            run.Append(new Text(text));
            paragraph.Append(run);
        }
        public static void AppendText(DocumentFormat.OpenXml.Wordprocessing.Body body, string text, XmlTextStyleDTO textStyleDTO)
        {
            Paragraph paragraph = new Paragraph();
            Run run = new Run();
            run.Append(new Text(text));
            paragraph.Append(run);

            ParagraphStyleId paragraphStyleId = new ParagraphStyleId() { Val = textStyleDTO.StyleId };
            var paragraphProperties = new ParagraphProperties();
            paragraphProperties.Append(paragraphStyleId);
            paragraph.Append(paragraphProperties);

            // WordStyle.SetBodyContentStyle(paragraph, textStyleDTO);
            body.Append(paragraph);

        }


        /// <summary>
        /// 获取正文
        /// </summary>
        public static string GetContent(System.Xml.Linq.XDocument xmlDocument, OpenXmlElement openXmlElement)
        {
            if (openXmlElement is Paragraph)
            {
                Paragraph paragraph = openXmlElement as Paragraph;
                var styleIdList = XmlStyle.GetStyleId(openXmlElement);
                if (styleIdList.Count == 0)
                {
                    var textList = paragraph.Descendants<Text>().ToList();
                    var textValueList = textList.Select(x => x.InnerText);
                    return string.Join("", textValueList);
                }
                foreach (var tempStyleId in styleIdList)
                {
                    IEnumerable<XElement> tempXElementList = XmlPackagePart.GetParagraphXMLStyleByStyleId(xmlDocument, tempStyleId);
                    foreach (var item in tempXElementList)
                    {
                        string tempStyleName = XmlPackagePart.GetValueByXElementNodeName(item, "name", "val");
                        tempStyleName = tempStyleName.ToLower();
                        if (!XmlPackageConst.TitleLevels.Any(x => x == tempStyleName))
                        {
                            //获取文本方式一
                            //paragraph.InnerText会获取到域代码,paragraph.InnerText获取值后还要处理域代码,所以暂时不用这种方式获取文本
                            // list.Add(paragraph.InnerText);
                            //获取文本方式二
                            var textList = paragraph.Descendants<Text>().ToList();
                            var textValueList = textList.Select(x => x.InnerText);
                            return string.Join("", textValueList);
                        }
                    }
                }
            }
            return string.Empty;
        }


        public static void RemoveSpace(Body body)
        {
            //OpenXmlElement spaceXmlElement = null;
            //// 查找最后一个空白段落
            //int lastParagraphIndex = -1;
            //for (int i = body.ChildElements.Count - 1; i >= 0; i--)
            //{
            //    if (body.ChildElements[i] is Paragraph para && para.InnerText.Trim().Length == 0)
            //    {
            //        spaceXmlElement = body.ChildElements[i];
            //        lastParagraphIndex = i;
            //        break;
            //    }
            //}
            //if (spaceXmlElement != null)
            //{
            //    spaceXmlElement.Remove();
            //}

            // 检查最后一个元素是否是空的段落或空的表格
            var lastElement = body.Elements<OpenXmlElement>().Last();
            if (lastElement != null)
            {
                if (lastElement is Paragraph para && para.InnerText.Trim().Length == 0)
                {
                    body.RemoveChild(lastElement);
                }

                //bool isEmptyParagraph = lastElement is Paragraph p && p.ChildElements.Count == 1 && p.ChildElements[0] is Run r && string.IsNullOrEmpty(r.Text);
                //bool isEmptyTable = lastElement is Table; // 假设空表格也表示空白页

                //if (isEmptyParagraph || isEmptyTable)
                //{
                //    body.RemoveChild(lastElement);
                //}
            }
        }

        public static bool IsDocumentEmpty(Body body)
        {
            bool isEmpty = true;

            // 查找段落（如果找到，文档非空）
            var paragraphs = body.Descendants<Paragraph>();

            foreach (Paragraph item in paragraphs)
            {
                string tempText = item.InnerText;
                if (!string.IsNullOrEmpty(tempText))
                {
                    isEmpty = false;
                    break;
                }
            }

            return isEmpty;
        }
    }
}
